<?php
namespace app\index\controller;
use app\index\controller\Home;
use think\Request;
use think\Session;
use think\captcha\Captcha;
class User extends Home
{

    /**
     * 跳转注册页面
     * @return \think\response\View
     */
    public function reg ()
    {
        $this->assign("title","注册");
        return view("User/reg");
    }

    /**
     * 注册时,发送邮件验证
     * 
     */
    public function send_mail()
    {

        $to_email = input('post.email');
        $name = input('post.username');
        $e_code = mt_rand(1000,9999);
        session('to_email',$to_email);
        session('e_code',$e_code);

        $email_nickname = 'FLY论坛官方';
        $data =array('mail_to' =>$to_email ,'email_name'=>$email_nickname );
        $subject = 'FLY论坛邮箱验证';
        $message = "
<pre>
欢迎加入FLY社区,
你的用户名是{$name}:
你的验证码是{$e_code};
</pre>";
        $a = new Home();
        $a->web_config();
        $res = send_email($data['mail_to'], $subject, $message, $data['email_name']);
        return json($res);
    }


    /**
     * 注册 把信息录入数据库
     */
    public function regDo ()
    {
    	//判断是否是post提交
    	if(Request::instance()->isPost()){ // request()->isPost() 助手函数,效果一样
    		// dump(Request::instance()->post());
    		// dump(input("post."));
    		//判断验证码是否正确
//    		$code = input("post.vercode");
//    		if(!$this->checkVerify($code)){
//    			$this->error("验证码错误");
//    		}
            //判断ecode是否正确
        // dump(session('e_code'));die;
            $e_code = session('e_code');
            $ecode = input("post.ecode");
            if($ecode != $e_code){
                $this->error('邮箱验证码错误');
            }

    		//获取传来的数据
            $data['name'] = input("post.username");
            $data['email'] = input("post.email");
            $data['sex'] = input("post.sex");
            $data['pwd'] = md5(input("post.pass"));
            $data['create_time'] = date("Y-m-d H:i:s");
    		// 实例化模型
    		$user = model("user");
            $result = $user->reg($data);
            switch($result){
                case 0:$this->error("注册失败");break;
                case 1:$this->success("注册成功",url('Index/index'));break;
                case 2:$this->error("该邮箱已被注册");break;
            }
    	}
    }

    /**
     * 跳转登录页面
     * @return \think\response\View
     */
    public function login ()
    {
        $this->assign("title","登录");
        return view("User/login");
    }

    /**
     * 登录验证
     */
    public function loginDo ()
    {
    	if(Request::instance()->isPost()){
    		// dump(input('post.'));
    		//获取邮箱和密码
    		$email = input("post.email");
    		$pwd = md5(input("post.pass"));
    		$vercode = input("post.vercode");

            //根据邮箱查用户id
            //实例化model模型
            $user = model("user");
            $info = $user ->selectUser(["email"=>$email]);
            if(empty($info)){
                $this->error("邮箱不存在");
            }
            $id = $info['id'];
            //判断用户是否有权限 登录
            $this ->judgeAction($id);
			//比较验证码
			if(!$this->checkVerify($vercode)){
    			$this->error("验证码错误");
    		}
            $data['email'] = $email;
            $data['pwd'] = $pwd;


    		// 调用user 模型中的login方法,成功返回1 失败返回0
			$num = $user->login($data);
            
			if($num > 0){
				$this->success("成功登录!!!",url("Index/index"));
			}else{
				$this->error("邮箱或密码有误!!!");
			}
    	}
    }

    /**
     * 退出登录
     **/
    public function loginOut ()
    {
    	Session::delete("home");
    	$this->success("已退出登录",url("Index/index"));
    }

    /**
     * 跳转个人中心的基本设置
     * @return \think\response\View
     */
    public function set ()
    {
        $this->isLogin();
        $this->assign("title","基本设置");
        //根据邮箱查个人的所有信息
        $email = input("session.home.email");
        $user = model("user");
        $info = $user->selectUser(['email'=>$email]);
        $this->assign("userinfo",$info);

        $qq_field = db('user')->where('id',session('home.id'))->find();
        $qq_field = $qq_field['qq_only_field'];
        $this->assign('qq_field',$qq_field);
        return view("User/set");
    }

    /**
     * 跳转个人中心
     * @return \think\response\View
     */
    public function userCenter ()
    {
        $this->isLogin();
        //接受参数
        $action = empty(Request::instance()->param("action")) ? "send" : Request::instance()->param("action") ;
        $this->assign("action",$action);
        //获得用户id
        $user_id = session("home.id");
        //根据用户id查看他的发帖数目和帖子
        $card = model("card");
        $list = $card->queryAllCardById($user_id);
        $card_num = count($list['data']);
        $this->assign("sendCardList",$list['data']);
        $this->assign("sendCardPage",$list['page']);
        $this->assign("sendCardNum",$card_num);

        //根据用户id查看他的收藏帖子数目和帖子
        $collect = model("collect");
        $list1= $collect->queryCollectByUserId($user_id);
        $collect_num = count($list1['data']);
        $this->assign("collectCardList",$list1['data']);
        $this->assign("collectCardPage",$list1['page']);
        $this->assign("collectCardNum",$collect_num);
        $this->assign("title","个人中心");
        return view("User/userCenter");
    }

    /**
     * 跳转我的消息
     * @return \think\response\View
     */
    public function message ()
    {
        $this->isLogin();
        //获得用户id
        $user_id = session("home.id");
        //根据用户id查询他的所有帖子的评论
        $eval = model("evaluate");
        $list = $eval->queryEvaluateById($user_id);
        $this->assign("messageList",$list['data']);
        $this->assign("messagePage",$list['page']);
        $this->assign("total",$list['total']);
        $this->assign("title","我的消息");
        return view("User/message");
    }

    /**
     * 跳转我的主页
     * @return \think\response\View
     */
    public function home ()
    {
        //如果有参数传进来,就是别人查看该用户的主页
        if(!empty(Request::instance()->param("id"))){
//            $this->isLogin();
            //获得user_id
            $id = Request::instance()->param("id");
        }else{
            //反之,则是自己看自己的主页
            $this->isLogin();
            $id = session("home.id");
        }
        //根据id查询个人信息
        $user = model("user");
        $userinfo = $user->selectUser(["id"=>$id]);
        $this->assign("userinfo",$userinfo);

        //根据id查看发帖数据
        $card = model("card");
        $cardList = $card->queryAllCardById($id);
        $this->assign("cardList",$cardList['data']);
        $this->assign("cardPage",$cardList['page']);

        //根据id 查看该用户的评论
        $eval = model("evaluate");
        $evalList = $eval->queryAllEvalByUserId($id);
        $this->assign("evalList",$evalList['data']);
        $this->assign("evalPage",$evalList['page']);


        $this->assign("title","我的主页");
        return view("User/home");
    }

    /**
     * 跳转到 找回我的密码 的页面
     * @return \think\response\View
     */
    public function findPwd ()
    {
    	$this->assign("title","找回密码");
        return view("User/findPwd");
    }

    /**
     * 找回密码第一步 判断邮箱是否正确
     */
    public function findPwdDo ()
    {
    	if(Request()->isPost()){
    		//获取传过来的数据
    		$email = input("post.email");
    		$code = input("post.vercode");

    		//判读验证码是否正确
    		if(!$this->checkVerify($code)){
    			$this->error("验证码错误");
    		}

    		//向数据库查询该邮箱是否存在
    		//实例化model
    		$user = model("user");
    		$info = $user->selectUser(["email"=>$email]);
    		if(!empty($info)){
    			Session::set("email",$email);
    			$this->success("已向你的邮箱发送邮件,从你的邮件去重置密码",url("User/rePwd"));
    		}else{
    			//如果$info为空 ,则该邮箱不存在
    			$this->error("该邮箱不存在");
    		}

    	}
    }

    /**
     * 跳转到 重置我的密码 的页面
     * @return \think\response\View
     */
    public function rePwd ()
    {
    	$this->assign("title","设置新密码密码");
        return view("User/rePwd");
    }

    /**
     * 设置新密码
     */
    public function rePwdDo ()
    {
    	if(Request()->isPost()){
    		//获取传过来的数据
    		$pass = md5(input("post.pass"));
    		$repass = md5(input("post.repass"));
    		$code = input("post.vercode");
    		$email = input("session.email");
    		// dump($email);
    		//判读验证码是否正确
    		if(!$this->checkVerify($code)){
    			$this->error("验证码错误");
    		}

    		//判读两次密码输出是否一致
    		if($pass != $repass){
    			$this->error("两次密码输入不一致");
    		}
    		//实例化model
    		$user = model("user");
    		$num = $user->updateUser(["email"=>$email],["pwd"=>$pass,"update_time"=>date("Y-m-d H:i:s")]);
    		if($num > 0){
    			Session::delete("email");
    			$this->success("重置密码成功",url("User/login"));
    		}else{
    			//如果$info为空 ,则该邮箱不存在
    			$this->error("重置密码失败");
    		}

    	}
    }

    public function repass ()
    {
        if(Request::instance()->isPost()){
            $this->isLogin();
            //就收数据
            $pass = md5(Request::instance()->param("nowpass"));//旧密码
            $newpass = md5(Request::instance()->param("pass"));//新密码
            $repass = md5(Request::instance()->param("repass"));//再次输入的新密码

            if($newpass != $repass){
                $this->error("两次密码输入不一致");
            }

            //比对旧密码是否正确
            $email = session("home.email");
            $data["email"] = $email;
            $data["pwd"] = $pass;

            $user = model("user");
            $res = $user -> selectUser($data);
            if(empty($res)){
                $this->error("旧密码输入错误");
            }
            $Data["pwd"] = $newpass;
            $Data["update_time"] = date("Y-m-d H:i:s");

            $result = $user -> updateUser(["email"=>$email],$Data);
            if($result > 0){
                $this->success("修改密码成功");
            }else{
                $this->error("修改密码失败");
            }
        }
    }

    //我的资料修改保存
    public function saveSetUser ()
    {
    	if(Request()->isPost()){
            $this->isLogin();
    		//获取传过来的数据
            $name = Request::instance()->param("username");
            $sex = Request::instance()->param("sex");
            $city = Request::instance()->param("provice");
            $sign = Request::instance()->param("sign");

            //根据名字查询数据库,看有没有重名的
            $user = model("user");
            $result = $user->selectUser(['name'=>$name]);
            if(!empty($result) && $name!=$result['name']){
                $this->error("该昵称已存在");
            }

            $data["name"]=$name;
            $data["sex"]=$sex;
            $data["city"]=$city;
            $data["sign"]=$sign;
            $data["update_time"]=date("Y-m-d H:i:s");
//            dump($data);die;
            //获取登录人的邮箱
            $email = session("home.email");
            $res = $user->updateUser(['email'=>$email],$data);

            if(!empty($res)){
                $this->redirect("User/set");
            }else{
                $this->error("更改失败");
            }
    	}
    }

    /**
     * 修改头像
     * @return \think\response\Json
     */
    public function uploadHeadImg()
    {
        $ret = array();
//        echo $_FILES;die;
//        dump($_FILES);die;
        if($_FILES["file"]["error"] > 0){
            $ret["message"] = $_FILES["file"]["error"];
            $ret["status"] = 0;
            $ret["src"] = "";
            return json($ret);
        }else{
            $pic =  $this->upload();
            if($pic['info']== 1){
                $url = '/uploads/'.$pic['savename'];
                //上传成功后,把图片路径存到用户表
                $user = model("user");
                $urlName = substr($pic['savename'],11);
                $user_id = session("home.id");
                //先查看原先的头像,如果没有,直接跟新,如果有,先把图片文件删除在更新
                $result = $user->selectUser(["id"=>$user_id]);
                if(!empty($result)){
                    //获取图片文件名
                    $url = $result['image'];
                    $url = get_img_url(ROOT_PATH."/public/upload/headImg",$url,0);
                    @unlink($url);
                }
                $user -> updateUser(["id"=>$user_id],["image"=>$urlName]);
                //把用户的信息放入到session中
                Session::set("home.image",$urlName);
            }  else {
                $ret["message"] = $this->error($pic['err']);
                $ret["status"] = 0;
            }
            $ret["message"]= "图片上传成功！";
            $ret["status"] = 1;
            $ret["src"] = $url;
            $ret["src1"] = ROOT_PATH."/public/upload/headImg";
            return json($ret);
        }
    }

    //图片上传代码
    private  function upload(){
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'headImg');
        $reubfo = array();  //定义一个返回的数组
        if($info){
            $reubfo['info']= 1;
            $reubfo['savename'] = $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            $reubfo['info']= 0;
            $reubfo['err'] = $file->getError();
        }
        return $reubfo;
    }



    //qq绑定
    public function qqlogin()
    {
        $a = new Home();
        $web_config = $a->web_config();
        $qqOAuth = new \Yurun\OAuthLogin\QQ\OAuth2(QQ_ID, QQ_KEY, 'http://localhost/fly_forum/public/index.php/index/user/qqcallback');
        $url = $qqOAuth->getAuthUrl();
        session('YURUN_QQ_STATE',$qqOAuth->state);
        header('location:' . $url);
    }
    //qq登录


    //qq登录回调方法
    public function qqcallback()
    {
        // 获取accessToken
        $qqOAuth = new \Yurun\OAuthLogin\QQ\OAuth2('101459905', '6081e85cb545465e35e3bfbe6e3c0aee', 'http://localhost/fly_forum/public/index.php/index/user/qqcallback');

        $accessToken = $qqOAuth->getAccessToken(session('YURUN_QQ_STATE'));

        // 调用过getAccessToken方法后也可这么获取
        // $accessToken = $qqOAuth->accessToken;
        // 这是getAccessToken的api请求返回结果
        // $result = $qqOAuth->result; 
        // 用户资料
        $userInfo = $qqOAuth->getUserInfo();
        
        // 存入cookie
        cookie('q_name',$userInfo['nickname'],6000);//昵称
        cookie('figureurl',$userInfo['figureurl'],6000);//头像
        // dump(cookie('q_name')); die;
        // 这是getAccessToken的api请求返回结果
        // $result = $qqOAuth->result;

        // 用户唯一标识
        $openid = $qqOAuth->openid;
        cookie('qq_openid',$openid,6000);//头像


        //保存进数据库
        $user_id = session('home.id') == null?'':session('home.id');
        //如果为空,执行执行登录操作
        if($user_id == ''){
            //查询数据库zhong是否存在,
            $res = db('user')->where('qq_only_field',$openid)->find();
            if($res){
                // 若果存在,直接登录
                $home['name'] = $res['name'];
                $home['email'] = $res['email'];
                $home['image'] = $res['image'];
                $home['level'] = $res['level'];
                $home['id'] = $res['id'];
                //把用户的信息放入到session中
                Session::set("home",$home);
               $this->success('登录成功',url('Index/index'));
            }else{
               //如果不存在,数据库添加新用户
               $data = ['name' => $userInfo['nickname'], 'qq_only_field' => $openid ,'pwd'=>'e10adc3949ba59abbe56e057f20f883e'];
               $res = db('user')->insert($data);
               $userId = db('user')->getLastInsID();
               $home['name'] = $userInfo['nickname'];
               // $home['email'] = $data['email'];
               // $home['image'] = $info['image'];
               $home['level'] = 1;
               $home['id'] = $userId;
               //把用户的信息放入到session中
               Session::set("home",$home);
               $this->success('登录成功',url('Index/index'));
            }
        }else{
            //如果不为空,执行绑定QQ操作
            //先判断此QQ是否已被绑定
            $res = db('user')->where('qq_only_field',$openid)->find();
            if($res){
                $this->error("QQ已绑定账号:{$res['name']},请先解绑",'User/set');
            }else{
                $res = db('user')->where('id',$user_id)->update(['qq_only_field' => $openid]);
                if($res==1){
                    $this->success('QQ绑定成功','index/index');
                }else{
                    $this->error('QQ绑定失败','index/index');
                }
            }
        }
    }

    public function qqout()
    {
        $user_id = session('home.id');
        $res = db('user')->where('id',$user_id)->update(['qq_only_field' => '0']);
        if($res==1){
            $this->success('QQ解绑成功','index/index');
        }else{
            $this->error('QQ解绑失败','index/index');
        }


    }




















    
}
?>